package karileet.meeting.profile.service;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import karileet.meeting.profile.ProfileConf;
import karileet.meeting.profile.SoundManager;
import karileet.meeting.profile.model.ThirdParty;

import java.util.List;

/**
 * Service for accessibility events
 * <p/>
 * Created by markus on 27.10.14.
 */
public class ThirdPartyService extends AccessibilityService {
    @Override
    public void onInterrupt() {
        Log.d(ProfileConf.APP, "Accessibility service interrupted");
    }

    @Override
    public void onServiceConnected() {
        Log.d(ProfileConf.APP, "Accessibility service is enabled");
        setAccessibilityEnabledFlag();
        // Set the type of events that this service wants to listen to.  Others
        // won't be passed to this service.
        AccessibilityServiceInfo info = new AccessibilityServiceInfo();
        info.eventTypes = AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED;
        ProfileConf state = new ProfileConf(getApplicationContext());
        ThirdParty tp = state.getThirdPartyApps();
        List<String> packageNames = tp.toStringArray();
        info.packageNames = packageNames.toArray(new String[packageNames.size()]);
        // Set the type of feedback your service will provide.
        info.feedbackType = AccessibilityServiceInfo.FEEDBACK_AUDIBLE;
        info.notificationTimeout = 100;
        this.setServiceInfo(info);
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {

        ProfileConf pc = new ProfileConf(getApplicationContext());
        if (event.getEventType() == AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED && pc.isProfileEnabled()) {
            Log.d(ProfileConf.APP, "Got accessibility event from: " + event.getPackageName().toString());
            SoundManager sm = new SoundManager(getApplicationContext());
            sm.play(pc.getBeepVolume());
        }
    }

    /**
     * Store a mark about accessibility service being enabled or disabled
     */
    private void setAccessibilityEnabledFlag() {
        ProfileConf pc = new ProfileConf(getApplicationContext());
        pc.setAccessibilityEnabled(true);
    }
}
